package com.tianji.aigc.config;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import jakarta.annotation.PostConstruct;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
@Getter
@Configuration
@RequiredArgsConstructor
public class TitlePromptConfig {
    // 用于与 Nacos 配置中心进行交互，比如获取配置、监听配置变更等。
    private final NacosConfigManager nacosConfigManager;
    private final TitleProperties titleProperties;

    // 使用原子引用，保证线程安全，底层是CAS（Compare-And-Swap）机制
    private final AtomicReference<String> titleSystemMessage = new AtomicReference<>();

    @PostConstruct // 初始化时加载配置
    public void init(){
        // 读取配置文件
        loadConfig(titleProperties.getSystem().getTitle(), titleSystemMessage);
    }

    private void loadConfig(TitleProperties.System.Title chat, AtomicReference<String> target) {

        try {
            String dataId = chat.getDataId();
            String group = chat.getGroup();
            long timeOutMs = chat.getTimeoutMs();

            // 1、主动读取配置
            String config = nacosConfigManager.getConfigService().getConfig(dataId, group, timeOutMs);
            target.set(config);
            log.info("从Nacos配置中心加载配置{}成功：内容为{}", target, config);

            // 2、添加监听器，实现配置变更时自动更新
            nacosConfigManager.getConfigService().addListener(dataId, group, new Listener() {
                @Override
                public Executor getExecutor() {
                    return null; // 使用 Nacos 客户端的默认线程池
                }

                @Override
                public void receiveConfigInfo(String s) {
                    target.set(s);
                    log.info("监听到配置文件更新，更新配置文件：{}", s);
                }
            });
        } catch (NacosException e) {
            log.error("监听配置时发生异常：", e);
        }
    }

}
